package com.chaos.auth.helper;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Deprecated
public class HmacMd5Util {

    public static String hmacMd5(String key, String data, boolean isUpper) {
        try {
            // 将密钥转换为字节数组
            byte[] keyBytes = key.getBytes("UTF-8");

            // 创建HMAC对象，使用MD5哈希函数和密钥
            Mac mac = Mac.getInstance("HmacMD5");
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "HmacMD5");
            mac.init(secretKeySpec);

            // 将待签名数据转换为字节数组，并写入HMAC对象
            byte[] dataBytes = data.getBytes("UTF-8");
            byte[] hashedBytes = mac.doFinal(dataBytes);

            // 将HMAC值转换为十六进制字符串
            StringBuilder hexString = new StringBuilder(2 * hashedBytes.length);
            for (byte b : hashedBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            String signature = hexString.toString();

            // 根据isUpper参数确定是否转换为大写
            if (isUpper) {
                signature = signature.toUpperCase();
            }

            return signature;

        } catch (NoSuchAlgorithmException | InvalidKeyException | java.io.UnsupportedEncodingException e) {
            throw new RuntimeException("Failed to calculate HMAC-MD5", e);
        }
    }

    public static void main(String[] args) {
        String key = "secretkey";
        String data = "Hello, World!";
        boolean isUpper = true;

        String hmacMd5Signature = hmacMd5(key, data, isUpper);
        System.out.println("HMAC-MD5 Signature: " + hmacMd5Signature);
    }
}
